package com.fowo.api.common.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ModelBuildEventListener;

import java.util.HashMap;
import java.util.Map;

/**
 * 将 Excel 直接处理成 List&lt;Map&gt; 格式
 * @author yl_ls
 */
public class ToMapListener extends ModelBuildEventListener {
    private final Map<Integer, String> indexFieldMap = new HashMap<>();

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> cellDataMap, AnalysisContext context) {
        for(Map.Entry<Integer, ReadCellData<?>> entry : cellDataMap.entrySet()) {
            indexFieldMap.put(entry.getKey(), entry.getValue().getStringValue());
        }
    }

    @Override
    public void invoke(Map<Integer, ReadCellData<?>> cellDataMap, AnalysisContext context) {
        Map<String, Object> rowData = new HashMap<>();
        for(Map.Entry<Integer, ReadCellData<?>> entry : cellDataMap.entrySet()) {
            final String columnName = indexFieldMap.get(entry.getKey());
            if (columnName != null) {
                final ReadCellData<?> value = entry.getValue();
                if (value != null) {
                    if (value.getType() == CellDataTypeEnum.BOOLEAN) {
                        rowData.put(columnName, value.getBooleanValue());
                    }
                    else if (value.getType() == CellDataTypeEnum.STRING || value.getType() == CellDataTypeEnum.DIRECT_STRING) {
                        rowData.put(columnName, value.getStringValue());
                    }
                    else if (value.getType() == CellDataTypeEnum.NUMBER) {
                        rowData.put(columnName, value.getNumberValue());
                    }
                } else {
                    rowData.put(columnName, null);
                }
            }
        }
        context.readRowHolder().setCurrentRowAnalysisResult(rowData);
    }
}
